package com.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cloud.config.SecurityCloudConfig;
import com.cloud.config.amqp.DirectRabbitConfig;
import com.cloud.type.AlgorithmType;
import com.cloud.entity.ConvertTaskEntity;
import com.cloud.entity.ConvertTaskFileEntity;
import com.cloud.entity.ResultEntity;
import com.cloud.service.AlgorithmService;
import com.cloud.util.CommonUtil;
import com.cloud.util.HttpClientUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

import static com.cloud.util.constants.ErrorEnum.E_30001;

/**
 * @author Henry.Song
 * @version 2020/11/26
 * @description
 */
@Service
public class AlgorithmServiceImpl implements AlgorithmService {

    private static final Logger LOG = Logger.getLogger(AlgorithmServiceImpl.class.getName());

    @Autowired
    private SecurityCloudConfig securityCloudConfig;

    @Autowired
    private DirectRabbitConfig directRabbitConfig;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 调用算法服务
     *
     * @param convertTaskEntity
     * @return
     */
    @Override
    public ResultEntity callAlgorithm(ConvertTaskEntity convertTaskEntity) {
        AlgorithmType algorithmType = AlgorithmType.type(convertTaskEntity.getAlgorithmType());

        beforeRequest(convertTaskEntity);
        JSONObject request = prepareRequest(convertTaskEntity, algorithmType);

        // RabbitMQ
        if(algorithmType == AlgorithmType.DETECT_FIRE){
            rabbitTemplate.convertAndSend(securityCloudConfig.getAlgorithmDetectFireExchangeName(),"FireRouting",request.toString().getBytes(StandardCharsets.UTF_8));
            return CommonUtil.successResult();
        }else if(algorithmType == AlgorithmType.DETECT_FIRE_DOOR){
            rabbitTemplate.convertAndSend(securityCloudConfig.getAlgorithmDetectFireDoorExchangeName(),"FireDoorRouting",request.toString().getBytes(StandardCharsets.UTF_8));
            return CommonUtil.successResult();
        }else if(algorithmType==AlgorithmType.DETECT_FIRE_EXITS){
            rabbitTemplate.convertAndSend(securityCloudConfig.getAlgorithmDetectFireExitsExchangeName(),"FireExitsRouting",request.toString().getBytes(StandardCharsets.UTF_8));
            return CommonUtil.successResult();
        }else if(algorithmType==AlgorithmType.DETECT_FIRE_PERSON){
            rabbitTemplate.convertAndSend(securityCloudConfig.getAlgorithmDetectFirePersonExchangeName(),"FirePersonRouting",request.toString().getBytes(StandardCharsets.UTF_8));
            return CommonUtil.successResult();
        }else if(algorithmType==AlgorithmType.DETECT_FIRE_DEHAZING){
            rabbitTemplate.convertAndSend(securityCloudConfig.getAlgorithmDetectFireDehazingExchangeName(),"FireDehazingRouting",request.toString().getBytes(StandardCharsets.UTF_8));
            return CommonUtil.successResult();
        }
//        System.out.println(request);
//        String content = JSONObject.toJSONString(request);
//        String url = getURLfromAlgorithmType(algorithmType);
//        String respstr = HttpClientUtil.doPost(url, content, null);
//        ResultEntity requestRet = handleResponse(respstr);
//        return requestRet != null ? requestRet : CommonUtil.errorResult(E_30001);
        return CommonUtil.errorResult(E_30001);
    }

    ResultEntity handleResponse(String respstr) {
        if (respstr != null && respstr.length() > 0) {
            return JSON.parseObject(respstr, new TypeReference<ResultEntity>() {
            });
        }
        return null;
    }

    public void beforeRequest(ConvertTaskEntity convertTaskEntity) {
        for (ConvertTaskFileEntity taskFileEntity : convertTaskEntity.getTaskFiles()) {
            Integer fileId = taskFileEntity.getFileId();
            taskFileEntity.setFileId(fileId); // String转Integer
        }
    }

    public JSONObject prepareRequest(ConvertTaskEntity convertTaskEntity, AlgorithmType algorithmType) {
        JSONObject request = new JSONObject();
        request.put("taskType", convertTaskEntity.getTaskType());
        request.put("id", convertTaskEntity.getId());
        request.put("taskFiles", convertTaskEntity.getTaskFiles());
        request.put("algorithmType", algorithmType.getName());

        if (convertTaskEntity.getCoordPoints().size() > 0) {
            request.put("coordPoints", convertTaskEntity.getCoordPoints());
        }

        if (convertTaskEntity.getSkipCoordPoints().size() > 0) {
            request.put("skipCoordPoints", convertTaskEntity.getSkipCoordPoints());
        }

        if (convertTaskEntity.getCacheNumber() != 0) {
            request.put("cacheNumber", convertTaskEntity.getCacheNumber());
        }

        return request;
    }

    /**
     * 根据算法类型选择服务地址
     *
     * @param algorithmType
     * @return
     */
    private String getURLfromAlgorithmType(AlgorithmType algorithmType) {
        if (algorithmType == AlgorithmType.DETECT_FIRE_EXITS) {
            return securityCloudConfig.getAlgorithmDetectFireExitsURL();
        } else if (algorithmType == AlgorithmType.DETECT_FIRE_PERSON) {
            return securityCloudConfig.getAlgorithmDetectFirePersonURL();
        } else if (algorithmType == AlgorithmType.DETECT_FIRE_DEHAZING) {
            return securityCloudConfig.getAlgorithmDetectFireDehazingURL();
        } else if (algorithmType == AlgorithmType.DETECT_FIRE) {
            return securityCloudConfig.getAlgorithmDetectFireURL();
        } else if (algorithmType == AlgorithmType.DETECT_FIRE_DOOR) {
            return securityCloudConfig.getAlgorithmDetectFireDoorURL();
        } else {
            throw new IllegalArgumentException("unkown algorithmType: " + algorithmType);
        }
    }
}
